<template>
  <div class="resources-container">
    <div class="action-bar">
      <el-button type="primary" size="large" class="action-button" @click="showResourceDialog">
        <i class="el-icon-upload"></i> 上传文献
      </el-button>
      <el-select v-model="filterCategory" placeholder="类别筛选" clearable style="margin-left:20px; width:200px;">
        <el-option label="所有类别" value=""></el-option>
        <el-option label="简历指导" value="简历指导"></el-option>
        <el-option label="面试技巧" value="面试技巧"></el-option>
        <el-option label="职业规划" value="职业规划"></el-option>
        <el-option label="政策法规" value="政策法规"></el-option>
      </el-select>
      <el-input v-model="searchKeyword" placeholder="搜索文献" clearable prefix-icon="el-icon-search" style="margin-left:20px; width:200px;"/>
    </div>

    <div class="resource-list">
      <el-card
        v-for="res in displayedResources"
        :key="res.resource_id"
        class="resource-card"
        shadow="hover"
      >
        <template #header>
          <div class="resource-header">
            <span class="resource-title">{{ res.title }}</span>
            <div class="resource-actions" v-if="res.uploader_id === auth.userId">
              <el-button type="text" icon="el-icon-delete" @click="deleteResource(res.resource_id)" />
            </div>
          </div>
        </template>
        <div class="resource-content">
          <p>{{ res.content }}</p>
          <p class="resource-meta">
            类别: {{ res.category }} 上传者: {{ res.uploader_username }} 上传于: {{ formatDate(res.upload_time) }}
          </p>
        </div>
      </el-card>
    </div>

    <el-dialog title="上传文献" v-model="dialogVisible" width="50%">
      <el-form :model="newResource" label-width="100px">
        <el-form-item label="标题" required>
          <el-input v-model="newResource.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" required>
          <el-input type="textarea" rows="4" v-model="newResource.content" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="类别" required>
          <el-select v-model="newResource.category" placeholder="选择类别">
            <el-option label="简历指导" value="简历指导" />
            <el-option label="面试技巧" value="面试技巧" />
            <el-option label="职业规划" value="职业规划" />
            <el-option label="政策法规" value="政策法规" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitResource" :loading="loading">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useAuthStore } from '../store/auth'
import { ElMessage, ElMessageBox } from 'element-plus'

const auth = useAuthStore()
const resources = ref([])
const searchKeyword = ref('')
const filterCategory = ref('')
const loading = ref(false)
const dialogVisible = ref(false)
const newResource = ref({ title: '', content: '', category: '' })

const displayedResources = computed(() => {
  let list = resources.value
  if (filterCategory.value) {
    list = list.filter(r => r.category === filterCategory.value)
  }
  const key = searchKeyword.value.trim().toLowerCase()
  if (key) {
    list = list.filter(r =>
      r.title.toLowerCase().includes(key) ||
      r.content.toLowerCase().includes(key)
    )
  }
  return list
})

const fetchResources = async () => {
  loading.value = true
  try {
    const token = auth.token
    const res = await fetch('http://127.0.0.1:8000/api/resources', {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${encodeURIComponent(token)}`
      }
    })
    if (!res.ok) throw new Error(await res.text())
    resources.value = await res.json()
  } catch (err) {
    ElMessage.error('获取文献失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

const formatDate = (dt) => {
  if (!dt) return ''
  return new Date(dt).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const showResourceDialog = () => {
  newResource.value = { title: '', content: '', category: '' }
  dialogVisible.value = true
}

const submitResource = async () => {
  loading.value = true
  try {
    if (!newResource.value.title || !newResource.value.content || !newResource.value.category) {
      ElMessage.warning('请填写标题、内容和类别')
      return
    }
    const token = auth.token
    const userId = auth.userId
    const res = await fetch('http://127.0.0.1:8000/api/resources', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${encodeURIComponent(token)}`
      },
      body: JSON.stringify({
        ...newResource.value,
        uploader_id: userId
      })
    })
    if (!res.ok) throw new Error(await res.text())
    ElMessage.success('上传成功')
    dialogVisible.value = false
    fetchResources()
  } catch (err) {
    ElMessage.error('上传失败: ' + err.message)
  } finally {
    loading.value = false
  }
}

const deleteResource = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除此文献吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const token = auth.token
    const userId = auth.userId
    const res = await fetch(`http://127.0.0.1:8000/api/resources/${id}?user_id=${userId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${encodeURIComponent(token)}`
      }
    })
    if (!res.ok) throw new Error(await res.text())
    ElMessage.success('删除成功')
    fetchResources()
  } catch (err) {
    if (err !== 'cancel') ElMessage.error('删除失败: ' + err.message)
  }
}

onMounted(fetchResources)
</script>

<style scoped>
.resources-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}
.action-bar {
  margin-bottom: 20px;
}
.action-button {
  padding: 10px 20px;
  font-size: 16px;
}
.resource-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}
.resource-card {
  border-radius: 8px;
}
.resource-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.resource-title {
  font-weight: bold;
  font-size: 18px;
  color: #409EFF;
}
.resource-content {
  padding: 10px;
  font-size: 14px;
}
.resource-meta {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
</style> 